<template>
    <div>
        <el-card shadow="hover" class="box-card">
            <template #header>
                <div class="flex justify-between">
                    <span class="text-sm">订单统计</span>
                    <el-check-tag v-for="(item, index) in options" :key="index" :checked="crrubtn === item.value"
                        @change="onChange(item.value)">{{ item.text }}</el-check-tag>
                </div>
            </template>
            <div ref="el" id="chart" style="width: 100%;height:300px;"></div>
        </el-card>

    </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue"
import { statistics3 } from "~/api/index"
import * as echarts from 'echarts';
import { useResizeObserver } from '@vueuse/core'
// 当前选中
const crrubtn = ref("week")
const options = [{
    text: "近1个月",
    value: "month"
}, {
    text: "近1周",
    value: "week"
}, {
    text: "近24小时",
    value: "hour"
}]

function onChange(type) {
    crrubtn.value = type
    getData()

}

// 销毁之前
onBeforeUnmount(() => {
    if (myChart) echarts.dispose(myChart)
})

var myChart = null
onMounted(() => {
    var chartDom = document.getElementById('chart');
    if (chartDom) {
        myChart = echarts.init(chartDom);
        getData()
    }
 
})

function getData() {
    let option = {
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [],
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }
        ]
    };

    myChart.showLoading()
    statistics3(crrubtn.value).then(res => {
        option.xAxis.data = res.x
        option.series[0].data = res.y

        myChart.setOption(option);
    }).finally(() => {
        myChart.hideLoading()
    })
}

// 实时动态缩放视窗大小
const el = ref(null)
useResizeObserver(el, (entries) => {
    myChart.resize()
})     
</script>